package com.zjq.filter;

import com.zjq.pojo.User;

import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {

    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest servletRequest = (HttpServletRequest)request;
        HttpServletResponse servletResponse = (HttpServletResponse) response;
        HttpSession session = servletRequest.getSession();
        // 获得用户请求的URI
        String path = servletRequest.getRequestURI();
        System.out.println("用户请求的URI："+path);

        User username = (User) session.getAttribute("user");

        System.out.println(username);
        System.out.println("-=-=-=-=--=-=-"+session.getAttribute("user"));

        // 登陆页面无需过滤
        if(path.indexOf("user/tologin") > -1) {
            chain.doFilter(servletRequest, servletResponse);
            return;
        }
        if(path.indexOf("user/login") > -1) {
            chain.doFilter(servletRequest, servletResponse);
            return;
        }

        // 判断如果没有取到用户信息,就跳转到登陆页面
        if (username == null || username.equals("")) {
            // 跳转到登陆页面
            servletResponse.sendRedirect(servletRequest.getContextPath()+"/user/tologin");
        } else {
            // 已经登陆,继续此次请求
            System.out.println("==================================dofilter");
            chain.doFilter(request, response);
        }
    }

    public void destroy() {

    }
}
